import requests
import time
def get_csdn_hot():
    while True:
        news_ls = []
        for i in range(2):
            url = "https://blog.csdn.net/phoenix/web/blog/hot-rank?page=" + str(i) + "&pageSize=50"
            #print(url)
            # csdn做了校验，必须设置请求头中的User-Agent才能成功返回内容
            headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"}
            resp = requests.get(url,headers=headers)
            resp = resp.json()
            news = resp['data']
            for new in news:
                news_ls.append({"title":new.get('articleTitle'),"url":new.get('articleDetailUrl')})

        i = 0
        news_ls.reverse()
        for new in news_ls:
            i += 1
            print(("\033[1;37m" + str(i) + "\033[0m").center(50,"*"))
            print("\033[1;36m" + new.get('title') + "\033[0m")

        news_length = len(news_ls)
        # news_ls.reverse()
        user_input = input("输入新闻编号获取进一步访问的超链接,输入q/Q退出,输入r/R刷新热榜：")
        if user_input == 'q' or user_input == 'Q':
            break
        elif user_input == 'r' or user_input == 'R':
            continue
        elif user_input in [str(i) for i in range(1,news_length+1)]:
            news_index = eval(user_input) - 1
            print(news_ls[news_index].get('url'))
            print("\033[1;33m" + "按住Ctrl键，点击超链接进行访问" + "\033[0m")
            print('\033[5;31m'+'10s后自动刷新热榜'+'\033[0m')
            time.sleep(10)
            continue
        else:
            print("Invalid User Input.")
            print('\033[5;31m'+"3s后自动刷新热榜"+'\033[0m')
            time.sleep(3)
            continue
    print("Over,退出CSDN热搜!")

